package com.meihua.baoleyi.broadcast;

import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import com.google.gson.Gson;
import com.meihua.baoleyi.bean.BaseBean;
import com.meihua.baoleyi.ui.MainActivity;
import com.meihua.baoleyi.utils.SharedPreUtils;
import java.util.List;
import cn.jpush.android.api.JPushInterface;

/**
 * 激光推送的广播接收器
 * Created by liming on 2017/11/1
 */

public class MyJushReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent == null || intent.getExtras() == null) {
            return;
        }

        Bundle bundle = intent.getExtras();

        if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {
//            Log.d("jpush", "[MyReceiver] 接收Registration Id : " + regId);

        } else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {
//            Log.d("jpush", "[MyReceiver] 接收到推送下来的自定义消息: " + bundle.getString(JPushInterface.EXTRA_MESSAGE));
            //1.删除好友;2.添加请求;3.接受请求;4.拒绝请求;5.垫付消息;6.通知信息;
            String type = bundle.getString(JPushInterface.EXTRA_CONTENT_TYPE);


        } else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) {
            jpushMessage(intent, context);
        } else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
            if (!isRuning(context)) {
                openApp(context);
            } else if (!isAppForeground(context)) {
//                Log.d("jpush", "[MyReceiver] 用户点击回到app调回前台" + bundle.getString(JPushInterface.EXTRA_EXTRA));
                resumeApp(context);
            }

        } else if (JPushInterface.ACTION_RICHPUSH_CALLBACK.equals(intent.getAction())) {
//            Log.d("jpush", "[MyReceiver] 用户收到到RICH PUSH CALLBACK: " + bundle.getString(JPushInterface.EXTRA_EXTRA));
            //在这里根据 JPushInterface.EXTRA_EXTRA 的内容处理代码，比如打开新的Activity， 打开一个网页等..

        } else if (JPushInterface.ACTION_CONNECTION_CHANGE.equals(intent.getAction())) {
            boolean connected = intent.getBooleanExtra(JPushInterface.EXTRA_CONNECTION_CHANGE, false);
//            Log.d("jpush", "[MyReceiver]" + intent.getAction() + " connected state change to " + connected);
        } else {
//            Log.d("jpush", "[MyReceiver] Unhandled intent - " + intent.getAction());
        }


    }

    /**
     * 解析极光推送通知完成推送效果
     *
     * @param intent
     * @param context
     */
    private void jpushMessage(Intent intent, Context context) {
        Bundle bundle = intent.getExtras();
        if (!"1".equals(bundle.getString("name", "1"))) {
            return;
        }
        String message = bundle.getString(JPushInterface.EXTRA_EXTRA);
        //1.删除好友;2.添加请求;3.接受请求;4.拒绝请求;5.垫付消息;6.通知信息;
        String type = "";
        try {
            BaseBean bean = new Gson().fromJson(message, BaseBean.class);
            type = bean.getCode();
        } catch (Exception e) {
            return;
        }
        Log.d("jpush", "--message--" + message + "---type---" + type);

    }

    /**
     * 后台程序调回前台
     *
     * @param context
     */
    private void resumeApp(Context context) {
        ActivityManager manager = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> task_info = manager
                .getRunningTasks(20);
        Intent intent = new Intent();

        String className = "";

        for (int i = 0; i < task_info.size(); i++) {

            if ("meihua.liangliang".equals(task_info
                    .get(i).topActivity.getPackageName())) {
                System.out.println("后台  "
                        + task_info.get(i).topActivity
                        .getClassName());

                className = task_info.get(i).topActivity
                        .getClassName();

                //这里是指从后台返回到前台  前两个的是关键
                intent.setAction(Intent.ACTION_MAIN);
                intent.addCategory(Intent.CATEGORY_LAUNCHER);
                try {
                    intent.setComponent(new ComponentName(
                            context, Class.forName(className)));//
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
                // intent.setClass(context,
                // Class.forName(className));
                intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT
                        | Intent.FLAG_ACTIVITY_NEW_TASK
                        | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
                context.startActivity(intent);

            }

        }
    }

    /**
     * 开启app
     *
     * @param context
     */
    private void openApp(Context context) {
        // 通过包名获取要跳转的app，创建intent对象
        Intent intent = context.getPackageManager().getLaunchIntentForPackage("com.meihua.baoleyi");
// 这里如果intent为空，就说名没有安装要跳转的应用嘛
        if (intent != null) {
            // 这里跟Activity传递参数一样的嘛，不要担心怎么传递参数，还有接收参数也是跟Activity和Activity传参数一样
            intent.putExtra("name", "Liu xiang");
            intent.putExtra("birthday", "1983-7-13");
            context.startActivity(intent);
        } else {
//            // 没有安装要跳转的app应用，提醒一下
//            Toast.makeText(getApplicationContext(), "哟，赶紧下载安装这个APP吧", Toast.LENGTH_LONG).show();
        }
    }

    /**
     * 判断程序是否在前台运行
     *
     * @param context
     * @return true在前台，false在后台
     */
    private boolean isAppForeground(Context context) {
        boolean isForground = false;
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            List<ActivityManager.RunningAppProcessInfo> runningProcesses = am.getRunningAppProcesses();
            for (ActivityManager.RunningAppProcessInfo processInfo : runningProcesses) {
                //前台程序
                if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                    for (String pkgName : processInfo.pkgList) {
                        if (pkgName.equals(context.getPackageName())) {
                            isForground = true;
                        }
                    }
                }
            }
        } else {
            //@deprecated As of {@link android.os.Build.VERSION_CODES#LOLLIPOP}, 从Android5.0开始不能使用getRunningTask函数
            List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
            ComponentName componentInfo = taskInfo.get(0).topActivity;
            if (componentInfo.getPackageName().equals(context.getPackageName())) {
                isForground = true;
            }
        }

        return isForground;
    }


    /**
     * 判断某个界面是否在前台
     *
     * @param activity 接main
     * @return
     */
    private boolean isForeground(Class activity, Context context) {
        if (TextUtils.isEmpty(activity.getName())) {
            return false;
        }

        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(1);
        if (list != null && list.size() > 0) {
            ComponentName cpn = list.get(0).topActivity;
            if (activity.getName().equals(cpn.getClassName())) {
                return true;
            }
        }
        return false;
    }

    private boolean isRuning(Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(100);
        boolean isAppRunning = false;
        String MY_PKG_NAME = "com.meihua.baoleyi";
        for (ActivityManager.RunningTaskInfo info : list) {
            if (info.topActivity.getPackageName().equals(MY_PKG_NAME) || info.baseActivity.getPackageName().equals(MY_PKG_NAME)) {
                isAppRunning = true;
                Log.i("jpush", info.topActivity.getPackageName() + " info.baseActivity.getPackageName()=" + info.baseActivity.getPackageName());
                break;
            }
        }
        return isAppRunning;
    }
}
